<?php
App::uses('AuthComponent', 'Controller/Component');
App::uses('DigestAuthenticate', 'Controller/Component/Auth');
class UsersController extends AppController{

	public $helper = array('Html' => 'Form' , 'Session');
	public $uses = array("User","Follow","Tweet");

	function index($id = null){
	}

	public function login(){
		$this->autoRender = false;
		if($this->request->is("post")){
			$username = $this->request->data["username"];
			$password= $this->request->data['password'];

			if(!isset($username) || !isset($password)){
				$data = array("status_code" => -1, "message" => "Log in faile.Data format wrong!!","entity" => array());
				return  json_encode($data);
			}

			// Check for data format
			if(!trim($username) || !trim($password)){
				$data = array("status_code" => -1, "message" => "Log in faile.Data format wrong!!","entity" => array());
				return json_encode($data);
			}else{
				$password = AuthComponent::password($this->request->data['password']);
			}

			$user = $this->User->find('first',array("conditions" =>
					array("username" => $username, "password" => $password),"recursive" => -1));

			if($user){
				$user["User"]["accesstoken"] = $this->User->updateAccessToken($username);
				if(!empty($this->request->data["regId"])){
					$reg = $this->request->data["regId"];
					$this->User->updateRegId($username,$reg);
				}
				unset($user["User"]["password"]);
				$data = array("status_code" => 0, "message" => "Log in success","entity" => $user);
				if($this->Session->write("user".$user["User"]["id"],$user["User"]["accesstoken"])){
					return json_encode($data);
				}
			}else{
				$data = array("status_code" => -1, "message" => "Log in faile.Username or password not right","entity" => array());
				return json_encode($data);
			}
		}
	}

	public function logout(){
		if(parent::loggedIn()){
			$this->Session->delete("user".$this->request->data["userid"]);
			$data = array("status_code" => 0, "message" => "Log out success","entity" => array());
			return json_encode($data);
		}else{
			$data = array("status_code" => -1, "message" => "Log out faile","entity" => array());
			return json_encode($data);
		}
	}


	public function add() {
		$this->autoRender = false;
		if ($this->request->is('post')) {
			if(empty($this->request->data["username"]) ||empty($this->request->data["password"])){
				$data = array("status_code" => -1, "message" => "Register Faile","entity" => array());
				//echo json_encode($data);die();
				return json_encode($data);
			}
				
			$username = $this->request->data["username"];
			$password = $this->request->data["password"];
				
			$user = $this->User->find("first",array("conditions" => array("username" =>$username),"recursive" => -1,
					"fields" => array("User.id")));
				
			if($user){
				$data = array("status_code" => -1, "message" => "Register failse, user was exist!!","entity" => array());
				//echo json_encode($data);die();
				return json_encode($data);
			}
				
			if(!empty($this->request->data["screenname"])){
				$screen_name = $this->request->data["screenname"];
			}else{
				$screen_name = "";
			}

			
			if($_FILES){
				$avarta = $this->uploadfile();
			}else{
				$avarta = "";
			}
				
			$insert = array("username" => $username, "password" => $password, "screen_name" => $screen_name,"avatar" => $avarta);
			$this->User->create();
			$this->User->set($insert);
			$this->User->save();
				
			$userre = $this->User->find("first",array("conditions" => array("id" =>$this->User->id),"recursive" => -1,
					"fields" => array("User.id","User.username","User.email","User.avatar","User.screen_name")));
			$data = array("status_code" => 0, "message" => "Register success!!","entity" => $userre);
			echo json_encode($data);
			//return json_encode($data);
		}
	}

	private function  uploadfile(){
		$this->autoRender = false;
		$folderPath =  WWW_ROOT.str_replace('/', DS, IMAGE_AVATARS);

		if (!is_dir($folderPath)) {
			$this->Folder = new Folder();
			$flg = $this->Folder->create($folderPath, 0777);
			if (!$flg) {
				return null;
			};
		};

		//debug($_FILES);
		if (!empty($_FILES['avatar'])) {
			$filetypes = array("image/jpg","image/jpeg","image/gif","image/png");
			if(in_array($_FILES["avatar"]["type"],$filetypes)){
				$fileName = time().$_FILES['avatar']['name'];
				$uploadFile = $folderPath . basename($fileName);
				move_uploaded_file($_FILES['avatar']['tmp_name'], $uploadFile);
				$name= WEBROOT.IMAGE_AVATARS.$fileName;
				return $name;
			}else{
				return null;
			}
		}else{
			return null;
		}
	}

	public function getUsers(){
		if($this->request->is("post")){
			$followers = $this->Follow->find("count",array("conditions" => array("Follow.following_id" => $this->request->data["get_userid"]) ,"recursive" => -1 )) ;
			$followings = $this->Follow->find("count",array("conditions" => array("Follow.follower_id" => $this->request->data["get_userid"]),"recursive" => -1 )) ;
			$tweets = $this->Tweet->find("count",array("conditions" => array("Tweet.user_id" => $this->request->data["get_userid"]),"recursive" => -1 )) ;
			
			$userFollow = $this->Follow->find("first",array("conditions" => 
					array("Follow.follower_id" => $this->request->data["userid"],"Follow.following_id" =>$this->request->data["get_userid"]),"recursive" => -1 )) ;
			if($userFollow){
				$followStatus = true;
			}else{
				$followStatus = false;
			}
			
			$content = array("followers" => $followers,"followings" => $followings,"tweets" => $tweets,"followStatus"=>$followStatus);
			$data = array("status_code" => 0, "message" => "OK","entity" => array($content));
			return json_encode($data);
		}else{
			$this->autoRender = true;
		}
	}
	public function suggestByName(){
		$this->autoRender = false;
		$err = null;
		$response;
		if($this->request->is('post')){
		
			if(!isset($this->request->data['name'])){
				$err .= "not found name param";
		
			}
// 			if(!isset($this->request->data['page'])){
// 				$err .= "not found page param";
			
// 			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				//check da retweet chua
				$name = $this->request->data['name'];
				//$page = $this->request->data['page'];
				//if($page<1)$page= 1;
				//$min = ($page-1)*10;
				$name= $name.'%';
				//debug($name);
				$query="SELECT     User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
				FROM     users AS User
				WHERE    User.username like '".$name."' 
				Group by User.username 
				Limit  20
				";
				
				// $suggestName = $this->User->getDataSource()->query($)
				
				$suggestName = $this->User->getDataSource()->query($query);
				//debug ($suggestName);
				$response = array("status_code" => 0,"message" => $err,"entity" =>$suggestName);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);
			 
		}
	}
    public function suggest(){
    	$this->autoRender = false;
    	$err = null;
    	$response;
    	if($this->request->is('post')){
    		
    		if(!isset($this->request->data['user_id'])){
    			$err .= "not found user_id param";
    				
    		}
    		//debug($this->request->data);
    		//debug(empty($err));
    		if(empty($err)){
    			//check da retweet chua
    			$userId = $this->request->data['user_id'];
    	        $query="SELECT     User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
    	        		FROM     users AS User
    	        		LEFT JOIN follows as Follow
    	        		ON    User.id = Follow.following_id and Follow.follower_id = $userId    
    	        		WHERE   isnull(Follow.id) and User.id <> $userId       
    	        		Limit 5";
    			$content = '';
    			$imageUrl = '';
    	
    			
    			$noneFowllow = $this->User->getDataSource()->query($query);
    			$response = array("status_code" => 0,"message" => $err,"entity" =>$noneFowllow);
    		}
    		else {
    			$response = array("status_code" => -1,"message" => $err,"entity" =>'');
    		}
    		echo json_encode($response);
    	
    	}
    }
	/* Ham phuc vu test cac chuc nang cua he thong*/


	// test log in
	public function tli(){
		$this->render('login');
	}

	// test thu truy cap den ham khi da login va chua login
	public function tm(){
		$this->render('mentions');
	}


	// test thu chuc nang logout
	public function tlo(){
		$this->render('logout');

	}
	/*  Ket thuc cac ham test chuc nang */
}